package com.keguoyu.easymvp.commons.receiver;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

public class Receivers {

  private static final ReceiverInterface<Object> DEFAULT = new ReceiverInterface<Object>() {
    @Override
    public void receive(Object target, Object accessible) {}

    @Override
    public Set<String> getAllNames() {
      return Collections.emptySet();
    }

    @Override
    public Set<Class> getAllTypes() {
      return Collections.emptySet();
    }

    @Override
    public void reset(Object target) {}
  };


  public static List<ReceiverInterface<Object>> receiverList(Object obj) {
    List<ReceiverInterface<Object>> list = new ArrayList<>();

    Class clazz = obj.getClass();
    try {
      while (clazz != null) {
        try {
          Class<?> loadClass = clazz.getClassLoader()
                  .loadClass(getReceiverClassName(clazz));
          list.add((ReceiverInterface<Object>) loadClass.newInstance());
        } catch (ClassNotFoundException ignore) {
        }
        clazz = clazz.getSuperclass();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (list.isEmpty()) {
      list.add(DEFAULT);
    }
    return list;
  }

  private static String getReceiverClassName(Class clazz) {
    String injectorClassName = clazz.getName();
    return injectorClassName + "$Receiver";
  }

}
